def open_r():
    '''
    读取文件
    :return:
    '''
    file = open('file2.txt', mode='r', encoding='utf-8')
    text = file.read()  # 读出来的都是字符串
    print(text)
    file.close()

    file2 = open('file1', 'r', encoding='utf-8')
    print(file2.read())
    file2.close()


def open_rw():
    '''
    读+写
    :return:
    '''
    file = open('file1', mode='r+', encoding='utf-8')
    print(file.read())

    file.write('world')  # 使用r+，内容在开头，原内容会被覆盖

    # 将文件指针重新定位到文件开始位置
    file.seek(0)
    print(file.read())

    file.close()


def open_w():
    '''
    写文件
    :return:
    '''
    file = open('file3', mode='w', encoding='utf-8')  # 文件存在会清空，文件不存在会创建
    file.write('hello world')
    file.close()


def open_a():
    '''
    追加信息
    :return:
    '''
    file = open('file3', mode='a', encoding='utf-8')
    file.write('hahaha')  # a模式在末尾追加
    file.close()


def use_readline():
    file = open('file2.txt','r',encoding='utf-8')  # 默认r模式，默认gbk
    while True:
        # 读取一行内容
        text = file.readline()

        # 判断是否读到内容，读到文件末尾是一个空字符串
        if not text:
            break
        print(text, end='')  # 防止换行


if __name__ == '__main__':
    # open_r()
    # open_rw()
    # open_w()
    # open_a()
    use_readline()
